package org.naxx.security.model.impl;

import java.util.HashSet;
import java.util.Set;

import org.naxx.security.algorithm.RuleCombiningAlgorithm;
import org.naxx.security.model.Policy;
import org.naxx.security.model.Rule;
import org.naxx.security.model.Target;
import org.naxx.security.model.expression.VariableDefinition;

/**
 * Two policies are equal if they have same id.
 */
public class PolicyImpl implements Policy {
	
	private String id;
	private String description;
	private RuleCombiningAlgorithm ruleCombiningAlgorithm;
	private Set<Rule> rules;
	private Target target;
	private Set<VariableDefinition> variableDefinitions;
	private String version = "1.0";

	public PolicyImpl() {
		this.variableDefinitions = new HashSet<VariableDefinition>();
		this.rules = new HashSet<Rule>();
	}

	public PolicyImpl(String id, String description, RuleCombiningAlgorithm ruleCombiningAlgorithm, 
			Set<Rule> rules, Target target, Set<VariableDefinition> variableDefinitions, String version) {
		this.id = id;
		this.description = description;
		this.ruleCombiningAlgorithm = ruleCombiningAlgorithm;
		this.rules = rules;
		this.target = target;
		this.variableDefinitions = variableDefinitions;
		this.version = version;
	}

	public String getDescription() {
		return this.description;
	}

	public String getId() {
		return this.id;
	}

	public RuleCombiningAlgorithm getRuleCombiningAlgorithm() {
		return this.ruleCombiningAlgorithm;
	}

	public Set<Rule> getRules() {
		return this.rules;
	}

	public Target getTarget() {
		return this.target;
	}

	public Set<VariableDefinition> getVariableDefinitions() {
		return this.variableDefinitions;
	}

	public String getVersion() {
		return this.version;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setRuleCombiningAlgorithm(
			RuleCombiningAlgorithm ruleCombiningAlgorithm) {
		this.ruleCombiningAlgorithm = ruleCombiningAlgorithm;
	}

	public void setTarget(Target target) {
		this.target = target;
	}

	public void setVersion(String version) {
		this.version = version;
	}	
	
	public void addVariableDefinition(VariableDefinition variableDefinition) {
		if(this.variableDefinitions.contains(variableDefinition)) {
			throw new IllegalArgumentException("Variable with id '" + variableDefinition.getVariableId() + "' " +
					"already present");
		}
		this.variableDefinitions.add(variableDefinition);
	}
	public void addRule(Rule rule) {
		this.rules.add(rule);
	}
	
	public boolean equals(Object obj) {
		if (this == obj) {
		    return true;
		}
		if (obj instanceof Policy) {
			Policy rhs = (Policy) obj;
			return this.id.equals(rhs.getId());
		}
		return false;
	}

	public int hashCode() {
		return this.id.hashCode();
	}
}
